package top.malaoshi.data;

import java.io.IOException;

/**
 * Table对象
 * @author mym
 *
 */
public class DataTable {
    private String name = "";

    private final DataColumns columns;

    private final DataRows rows;

    public DataIndexManager indexManager = new DataIndexManager();

    
    public DataTable(){
        columns = new DataColumns(this);
        rows = new DataRows(this);
    }
    public DataTable(String name){
        this.name = name;
        columns = new DataColumns(this);
        rows = new DataRows(this);
    }



    public String getName() {
        return name;
    }

    /**
     * 创建 DataRow 对象
     * 注意：创建后还需要调用 dataTable.Rows.Add(row) ，将 DataRow 添加到表中
     * @return
     */
    public DataRow newRow(){
        DataRow dr = new DataRow(columns.count());
        dr.setDataTable(this);
        return dr;
    }
    /**
     * 创建高级查询，查询后返回DataTable
     * @return
     */
    public DataAdvancedQuery createAdvancedQuery(){
        return new DataAdvancedQuery(this);
    }

    public DataRow[] select(String columnName, DataQuery.Option option, int value){
        return DataQuery.select(this,columnName, option, value);
    }
    public DataRow[] select(String columnName, DataQuery.Option option, double value){
        return DataQuery.select(this,columnName, option, value);
    }
    public DataRow[] select(String columnName, DataQuery.Option option, String value){
        return DataQuery.select(this,columnName, option, value);
    }

    public GroupBy groupBy(String ... columns){
        return new GroupBy(this).groupBy(columns);
    }
    public OrderBy orderBy(String column, OrderBy.Sort sort){
        return new OrderBy(this).orderBy(column,sort);
    }
    /**
     * 克隆表结构，不包含数据
     * @return
     */
    public DataTable clone(){
        DataTable retDataTable = new DataTable(this.getName());

        for(int i = 0,count = this.columns.count();i<count;i++){
            DataColumn dataColumn = this.columns.get(i);
            retDataTable.columns.add(dataColumn.getName(),dataColumn.getType());
        }
        return retDataTable;
    }

    /**
     * 复制表，同时复制了表结构和表中的数据
     * @return
     */
    public DataTable copy(){
        DataTable retDataTable = clone();

        for(int i = 0,count = this.rows.count();i<count;i++){
            DataRow dataRow = this.rows.get(i);
            retDataTable.rows.add(dataRow.toArray());
        }
        return retDataTable;
    }

    /**
     * 清空数据
     */
    public void clear(){
        this.rows.clear();
    }

    public DataColumns columns() {
        return columns;
    }

    public DataRows rows() {
        return rows;
    }
    public void writeJson(String path) throws IOException {
        DataFile.writeJson(this,path);
    }

}
